// 封装fetch,返回json
import fetch from "node-fetch";
import {pipeline} from 'stream';
import {promisify} from 'util';
import fs from "fs";
import chalk from "chalk";

async function fetchData(url) {
    try {
        const response = await fetch(url);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();
        return data;
    } catch (error) {
        console.error('Error fetching data:', error);
        throw error;
    }
}

// 返回下载流
async function fetchStream(url) {
    try {
        const response = await fetch(url);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.body;
    } catch (error) {
        console.error('Error fetching data:', error);
        throw error;
    }
}

const timeout = (ms, promise) =>
    new Promise((_, reject) => setTimeout(() => reject(new Error('Timeout')), ms)).then(() => promise);

export const fetchJsonDataWithTimeout = async (url, timeoutMs = 5000) => {
    try {
        return await timeout(timeoutMs, fetchData(url));
    } catch (error) {
        console.error('Request timed out:', error.message);
        throw error;
    }
};


export const downloadFile = async (url, localPath) => {
    try {
        const response = await fetch(url);
        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }

        const streamPipeline = promisify(pipeline);
        await streamPipeline(response.body, fs.createWriteStream(localPath));
        console.log(chalk.green(`Downloaded and saved to ${localPath}`));
    } catch (error) {
        console.error(chalk.red(`Error downloading file: ${error.message}`));
    }
};
